package editor.dxf;

import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;

public class DoorParser {
	private BufferedImage img;
	private BitSet b;

	public DoorParser(BufferedImage img2) {
		img = img2;

	}
	
	private boolean isPortal(int x, int y){
		if(b.get(x + y*img.getWidth()) == false){
			b.set(x + y*img.getWidth(), true); //no vuelve a entrar
			int c = img.getRGB(x, y);
			int  red = (c & 0x00ff0000) >> 16;
			//int  green = (c & 0x0000ff00) >> 8;
			int  blue = c & 0x000000ff;
			if(red == 0 && blue > 200)
				return true;
			return false;
		}else return false;
	}

	public List<DXFDoor> leerPuertas() {
		b = new BitSet(img.getHeight() * img.getWidth()); // para no repetir
															// portales
		ArrayList<DXFDoor> p = new ArrayList<DXFDoor>(255);

		for (int i = 0; i < img.getWidth(); i++) {
			for (int j = 0; j < img.getHeight(); j++) {
				if( isPortal(i, j) ){
					DXFDoor pta = addDoor(i, j);
					if(pta != null)	p.add(pta);
				}
			}
		}
		return p;
	}

	private DXFDoor addDoor(int i1, int j1) {
		DXFDoor p = new DXFDoor(null, null);
		//me fijo si es horizontal
		for (int i = i1+1; i < img.getWidth(); i++) {
			if(!isPortal(i, j1)){
				if(i>i1+3){ //mide al menos 3px
					p.setAdyacent(new Point2D.Float(i1, j1));
					p.setBisagra(new Point2D.Float(i-1, j1));
					return p;
				} else break; //me fijo si es vertical
			}
		}
		for (int j = j1+1; j < img.getHeight(); j++) {
			if(!isPortal(i1, j)){
				if(j>j1+3){ //mide al menos 3px
					p.setAdyacent(new Point2D.Float(i1, j1));
					p.setBisagra(new Point2D.Float(i1, j-1));
					return p;
				} else break;
			}
		}
		return null;
	}

}
